package cn.joeg.app.interceptor;

import cn.joeg.app.GCore;
import cn.joeg.app.GCoreContext;
import com.ecfront.dew.common.JsonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class GCoreHandlerInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(GCoreHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter(GCore.Constant.TOKEN_VIEW_FLAG);
        GCoreContext context = new GCoreContext();
        /**
         * 通过拦截器 把mesage记录到这次请求中的context中。
         * 每一次请求对应一个Context
         * token ：做api授权的时候用到
         */
        context.setId(GCore.Util.createUUID());
        context.setSourceIP(GCore.Util.getRealIP(request));
        context.setRequestUri(request.getRequestURI());
        context.setToken(token);
        GCoreContext.setContext(context);
        logger.trace("[{}] {}{} from {}", request.getMethod(), request.getRequestURI(), request.getQueryString() == null ? "" : "?" + request.getQueryString(), context.getSourceIP());
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
